//
//  LJIssueView.m
//  LajinLive
//
//  Created by 刘洋 on 16/8/25.
//  Copyright © 2016年 lajin. All rights reserved.
//

#import "IGIssueTopicView.h"
#import "IGIssueImageCollectionView.h"
#import "IGCommunityTableViewCell.h"
#import "IGCList4SearchVC.h"
#import "IGSearchVC.h"

@interface IGIssueTopicView()<UITextViewDelegate, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *layerView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger section;
@property (nonatomic, strong) IGIssueImageCollectionView *imageCollectionView;
@property (nonatomic, assign) BOOL isAllowChangeCircle;
@property (nonatomic, strong) YYLabel *chaLabel;

@end

@implementation IGIssueTopicView

- (instancetype)initWithFrame:(CGRect)frame communityModel:(IGCommunityModel *)communityModel {
    self = [self initWithFrame:frame];
    if (self) {
        _communityModel = communityModel;
        if (communityModel.cid) {
            self.isAllowChangeCircle = NO;
        } else {
            self.isAllowChangeCircle = YES;
        }
        if (_communityModel && [_communityModel.cTitle isEqualToString:NSLocalizedString(@"Art Talks", nil)]) {
            self.section = 2;
        } else {
            self.section = 1;
        }
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addNotifaction];
        
        [self createUI];
        [self setConstraint];
    }
    return self;
}
    
- (void)createUI
{
    [self addSubview:self.scrollView];
    [_scrollView addSubview:self.layerView];
    
    [_layerView addSubview:self.textView];
    [_layerView addSubview:self.chaLabel];
    [_layerView addSubview:self.imageCollectionView];
    [_layerView addSubview:self.tableView];
}

- (void)setConstraint
{
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(150);
    }];
    
    [_chaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_textView.mas_bottom).mas_offset(5);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(25);
    }];
    
    CGFloat vIheight = [IGIssueImageCollectionView getCellItemWidth] + 12;
    [_imageCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(_chaLabel.mas_bottom).offset(10);
        make.height.mas_equalTo(vIheight);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(_imageCollectionView.mas_bottom).offset(10);
        make.height.mas_equalTo(120);
    }];
}

#pragma mark - dealloc
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 懒加载

- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin)];
        _scrollView.contentSize = CGSizeMake(KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin + 1);
        _scrollView.delegate = self;
        _scrollView.scrollEnabled = YES;
        _scrollView.bounces = YES;
        _scrollView.showsVerticalScrollIndicator = YES;
    }
    return _scrollView;
}

- (UIView *)layerView
{
    if (!_layerView) {
        _layerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin)];
    }
    return _layerView;
}

- (YYLabel *)chaLabel {
    if (!_chaLabel) {
        _chaLabel = [YYLabel new];
        [self updateChaLabel:@"0/300"];
    }
    return _chaLabel;
}

- (void)updateChaLabel:(NSString *)chaText {
    NSMutableAttributedString *attributedText= [[NSMutableAttributedString alloc] initWithString:chaText];
    [attributedText setYy_font:[UIFont font16]];
    [attributedText setYy_color:[UIColor c1Color]];
    [attributedText yy_setTextHighlightRange:NSMakeRange(chaText.length - 4, 4) color:[UIColor c5Color] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
    }];
    _chaLabel.attributedText = attributedText;
}

- (UITextView *)textView
{
    if (!_textView) {
        _textView = [[IWTextView alloc] init];
        _textView.placeholder = NSLocalizedString(@"Don't hesitate to make comments, just like Van Gogh and Lei Feng.", nil);
        _textView.delegate = self;
    }
    return _textView;
}

- (IGIssueImageCollectionView *)imageCollectionView
{
    if (!_imageCollectionView) {
        _imageCollectionView = [[IGIssueImageCollectionView alloc] init];
    }
    return _imageCollectionView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor mainBackgroundColor];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

#pragma mark - Notification
- (void)addNotifaction
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageCollectionViewReloadNotifaction:) name:@"imageCollectionViewReloadNotifaction" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(customTextViewDidChange:) name:UITextViewTextDidChangeNotification object:self.textView];
}

- (void)customTextViewDidChange:(NSNotification *)obj
{
    UITextView *textView = (UITextView *)obj.object;
    
    bool isChinese;//判断当前输入法是否是中文
    if ([[textView.textInputMode primaryLanguage] isEqualToString: @"en-US"]) {
        isChinese = false;
    }
    else
    {
        isChinese = true;
    }
    
    if(textView == self.textView) {
        // 12位
        NSString *str = [[self.textView text] stringByReplacingOccurrencesOfString:@"?" withString:@""];
        if (isChinese) { //中文输入法下
            UITextRange *selectedRange = [self.textView markedTextRange];
            //获取高亮部分
            UITextPosition *position = [self.textView positionFromPosition:selectedRange.start offset:0];
            // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (!position) {
                if ( str.length>300) {
                    NSString *strNew = [NSString stringWithString:str];
                    [self.textView setText:[strNew substringToIndex:300]];
                    [self presentMessageTips:NSLocalizedString(@"Exceeding max word count. Input Not Available", nil)];
                }
                [self updateChaLabel:[NSString stringWithFormat:@"%zd/%zd", _textView.text.length, 300]];
            }
            else
            {
                
            }
        }else{
            if ([str length]>300) {
                NSString *strNew = [NSString stringWithString:str];
                [self.textView setText:[strNew substringToIndex:300]];
                [self presentMessageTips:NSLocalizedString(@"Exceeding max word count. Input Not Available", nil)];
            }
            [self updateChaLabel:[NSString stringWithFormat:@"%zd/%zd", _textView.text.length, 300]];
        }
    }
}

- (void)imageCollectionViewReloadNotifaction:(NSNotification *)notification
{
    NSArray *selectAssetsArr = (NSArray *)notification.object;
    CGFloat height = [IGIssueImageCollectionView getCellItemWidth];
    
    int rows = (int)(selectAssetsArr.count/4) + 1;
    if (selectAssetsArr.count >= 20) {
        rows--;
    }
    CGFloat zHeight = rows * (height + lineSpaceWidthImage) + lineSpaceWidthImage;
    
    [_imageCollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(_textView.mas_bottom).offset(10);
        make.height.mas_equalTo(zHeight);
    }];
    
    CGFloat maxHeight = CGRectGetMaxY(_textView.frame) + 10 + zHeight + 140;
    CGRect frame = _layerView.frame;
    if (maxHeight > KSCREENHEIGHT - NavigationMagin) {
        [_scrollView setContentSize:CGSizeMake(KSCREENWIDTH, maxHeight + 15 + 1)];
        frame.size.height = maxHeight + 15;
        [_layerView setFrame:frame];
    } else {
        [_scrollView setContentSize:CGSizeMake(KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin + 1)];
        frame.size.height = KSCREENHEIGHT - NavigationMagin;
        [_layerView setFrame:frame];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _scrollView) {
        [self endEditing:YES];
    }
}

#pragma mark - UITableViewDelegate、UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSArray *imgArr = @[@"community_selected", @"community_linked"];
    NSArray *titleArr = @[NSLocalizedString(@"Group", nil),NSLocalizedString(@"Associated Works", nil)];
    
    IGCommunityTableViewCell *cell = [IGCommunityTableViewCell cellWithTableView:tableView];
    if (indexPath.section == 0) {
        [cell dataWithImg:imgArr[0] title:titleArr[0] detail:self.communityModel.cid?[NSString stringWithFormat:@"#%@#", self.communityModel.cTitle]:NSLocalizedString(@"Please Select a Group", nil)];
    } else {
        [cell dataWithImg:imgArr[1] title:titleArr[1] detail:self.dataBase.aId?[NSString stringWithFormat:@"#%@#", self.dataBase.title]:NSLocalizedString(@"Associated Works", nil)];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.section;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10.f;
    } else {
        return 0.1f;
    }
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self endEditing:YES];
    
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0 && self.isAllowChangeCircle) {
        IGCList4SearchVC *listVC = [[IGCList4SearchVC alloc] initWithListType:IGCommunityListType4TopicPub];
        listVC.selectModel = self.communityModel;
        listVC.itemDidClick = ^(IGCommunityModel *model) {
            weakSelf.communityModel = model;
            if (weakSelf.communityModel && [weakSelf.communityModel.cTitle isEqualToString:@"艺术大家谈"]) {
                weakSelf.section = 2;
            } else {
                weakSelf.section = 1;
                weakSelf.dataBase = nil;
            }
            [weakSelf.tableView reloadData];
        };
        [UIViewController ig_pushViewController:listVC animated:YES];
    } else if (indexPath.section == 1) {
        IGSearchVC *searchVC = [[IGSearchVC alloc] init];
        searchVC.search4PubBlock = ^(IGArtWorkModel *dataBase){
            weakSelf.dataBase = dataBase;
            [weakSelf.tableView reloadData];
        };
        [UIViewController ig_pushViewController:searchVC animated:YES];
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
